import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);


// 导入获取用户信息接口 & 购物车数据
import { getUserInfo, getCartList } from "@/api";


export default new Vuex.Store({
  state: {
    token: sessionStorage.getItem('token') ? sessionStorage.getItem('token') : '',
    isLogin: sessionStorage.getItem('isLogin') ? sessionStorage.getItem('isLogin') : false,
    userInfo: null,
    cartList: [],
    badgeCount: 0,
    allChecked: false
  },
  getters: {
    getIsLogin (state) {
      // console.log('=======3=======');
      return state.isLogin
    },
    getToken (state) {
      return state.token
    },
    getBadgeCount (state) {
      return state.badgeCount
    },
    getCartData (state) {
      return state.cartList
    }
  },
  mutations: {
    setToken (state, params) {
      // console.log('----1-------');
      sessionStorage.setItem('token', params.token)
      sessionStorage.setItem('isLogin', true)
      state.token = params.token
      state.isLogin = true
      // console.log('----2------');
    },
    // 设置用户信息
    setUserInfo (state, params) {
      state.userInfo = params
    },
    // 设置购物车数据
    setCartList (state, params) {
      state.cartList = params
    },
    setBadgeCount (state, params) {
      state.badgeCount = params
    },
    setAllChecked (state, params) {
      state.allChecked = params
    }
  },
  actions: {
    getInfo (state) {
      console.log('可以在这里获取用户信息');
      // 登录完成 获取用户信息
      getUserInfo(res => {
        console.log('得到用户信息', res);
        state.commit('setUserInfo', res.data)
      })
    },
    getCartData (state) {
      getCartList((res) => {
        // 从购物车数据中得到 总商品数据量
        if (res.status === 0) {
          const list = res.data
          let count = 0
          list.forEach(element => {
            // 得到每件商品的数据
            count += element.count
            element.checked = false
          });
          state.commit('setBadgeCount', count)
          state.commit('setCartList', list)
        }

      });
    },
    // 处理单选事件
    changeChecked (state) {
      let checked = true
      state.getters.getCartData.forEach(item => {
        if (!item.checked) {
          checked = false
          return
        }
      })
      state.commit('setAllChecked', checked)
    }
  }
});
